import React, {useEffect, useState, useRef } from 'react'
import {message ,Button,Tabs,Divider,Popconfirm} from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect } from 'umi'
import { queryAwardPackageList,saveAndUpdateAwardPackage,getReAndPu,deleteAwardPackage,awardPackageBpm} from '../service'
import { awardStatusList, BPMStatusEnum, distributionStatusList } from '@/utils/constant'
import { formatNumber } from '@/utils/utils'
import CreateForm from './components/CreateForm'
import Details from './components/Details'
import moment from 'moment'
const  { TabPane } = Tabs;

const TableList = () => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [visible, setVisible] = useState(false);
  const [loading,setLoading] = useState(false);
  const [record,setRecord] = useState(null);
  const [reanpu,setReanpu] = useState([]);
  const [detailsVisible,setDetailsVisible] = useState(false);
  const [id,setId] = useState(null);

  useEffect(()=>{
    getReAndPu().then((res)=>{
      setReanpu(res);
    })
  }, []);

  const addAward = () =>{
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    setDetailsVisible(false);
    setRecord(null);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveAndUpdateAwardPackage(values).then((res)=>{
      if(res.flag){
        handleCancel();
        message.success('奖罚包操作成功！');
        actionRef.current.reload();
      }else{
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  const handleChangTabIndex = (key) => {
    if(key === '1'){
      actionRef.current &&  actionRef.current.reload();
    }else{
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const delAwardPackage = (id) => {
    deleteAwardPackage(id).then(res => {
      if(res.flag){
        message.success('删除成功！');
        actionRef.current.reload();
      }else{
        message.error(res.error);
      }
    })
  };

  const initiateAwardPackage = (id) => {
    awardPackageBpm(id).then(res => {
      if(res.flag){
        message.success('发起成功！');
        actionRef.current.reload();
        window.open(res.data);
      }else{
        message.error(res.error);
      }
    })
  };

  const updateAwardPackage = (record) => {
    setVisible(true);
    setRecord(record);
  };

  const details = (id) => {
    if(id){
      setId(id);
      setDetailsVisible(true);
    }
  };

  const columns = [
    {
      title: '流水号',
      dataIndex: 'serialNum',
    },
    {
      title: '申请日期',
      dataIndex: 'applyTime',
      hideInSearch: true,
      render: (text) => {
        return text != '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '申请人',
      dataIndex: 'applicantName',
    },
    {
      title: '申请人公司',
      dataIndex: 'orgname',
      hideInSearch: true,
    },
    {
      title: '申请人部门',
      dataIndex: 'unitname',
      hideInSearch: true,
    },
    {
      title: '奖罚名称',
      dataIndex: 'awardName',
    },
    {
      title: '奖罚种类',
      dataIndex: 'type',
      hideInSearch: true,
      render: (text) => {
        const res = reanpu.find((item) => item.code === text);
        return res ? res.name : text;
      }
    },
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      hideInSearch: true,
      render:(text) =>{
        return formatNumber(text)
      },
    },
    {
      title: '奖罚说明',
      dataIndex: 'remark',
      hideInSearch: true,
      ellipsis:true,
      width: 200
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: BPMStatusEnum
    },
    {
      title: '分配状态',
      dataIndex: 'distributionStatus',
      key:'distributionStatus',
      hideInSearch: true,
      render: (text) => {
        const res = distributionStatusList.find((item) => item.value === text);
        return res ? res.label : text
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          {(record.status === 0) && <>
            <a onClick={(e) => updateAwardPackage(record)}>修改</a>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => delAwardPackage(record.id)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical"/>
            <Popconfirm placement="topLeft" title={`是否确认发起?`} onConfirm={() => initiateAwardPackage(record.id)} okText="是" cancelText="否">
              <a>发起</a>
            </Popconfirm>
          </>}
          {(record.bpmUrl && record.status !== 0) && <><a onClick={() => window.open(record.bpmUrl)}>审批详情</a></>}
          {(record.status === 2) && <>
            <Divider type="vertical"/>
            <a onClick={(e) => details(record.id)}>分配详情</a>
          </>}
        </>
      ),
    }
  ];

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="1" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="1">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => queryAwardPackageList(params,[0,1])}
            columns={columns}
            toolBarRender={(action, { selectedRows }) => [
              <Button key={0} type="primary" onClick={() => addAward(null)}>新建</Button>,
            ]}
          />
          <CreateForm
            loading={loading}
            visible={visible}
            reanpu={reanpu}
            record={record}
            onCancel={handleCancel}
            onSubmit={handleSubmit}
          />
        </TabPane>
        <TabPane tab="已办理" key="2">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => queryAwardPackageList(params,[2])}
            columns={columns}
          />
          <Details
            visible={detailsVisible}
            id={id}
            reanpu={reanpu}
            onCancel={handleCancel}/>
        </TabPane>
      </Tabs>
    </PageHeaderWrapper>
  )
};

export default connect(({}) => ({
}))(TableList)
